package org.xiaov.extra.mail.strategy.impl;

import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.xiaov.bean.mail.Mail;
import org.xiaov.core.string.StringHelper;
import org.xiaov.extra.mail.strategy.MailStrategy;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * <p>
 * html格式的邮件
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/2/26 12:36
 */
@Service
public class HtmlMail implements MailStrategy {
    @Resource
    private JavaMailSender javaMailSender;

    @Override
    public void sendMail(Mail mail) {
        MimeMessage message = javaMailSender.createMimeMessage();

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mail.getFrom());
            helper.setTo(mail.getTo());
            helper.setSubject(mail.getTitle());
            helper.setText(mail.getContent(), true);
            javaMailSender.send(message);
            log.info("html邮件已经发送给{}。", StringHelper.printArray(mail.getTo()));
        } catch (MessagingException e) {
            log.error("发送html邮件时发生异常！", e);
            throw new MailSendException("发送html邮件时发生异常！", e);
        }
    }
}
